package com.hengxinguotong.zhihuichengjian.ui.engineering.task;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.MyFragmentPagerAdapter;
import com.hengxinguotong.zhihuichengjian.bean.MenuBean;
import com.hengxinguotong.zhihuichengjian.bean.MenuListRes;
import com.hengxinguotong.zhihuichengjian.bean.TaskCountRes;
import com.hengxinguotong.zhihuichengjian.fragment.TaskFragment;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.MyRadioGroup;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 任务列表
 * Created by liux on 2017/3/27.
 */

public class TaskListActivity extends BaseActivity implements ViewPager.OnPageChangeListener {
    private static final String TAG = "TaskListActivity";
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.daishouli)
    RadioButton daishouli;
    @BindView(R.id.daishouli_tv)
    HXTextView daishouliTv;
    @BindView(R.id.daijiancha)
    RadioButton daijiancha;
    @BindView(R.id.daijiancha_tv)
    HXTextView daijianchaTv;
    @BindView(R.id.chulizhong)
    RadioButton chulizhong;
    @BindView(R.id.chulizhong_tv)
    HXTextView chulizhongTv;
    @BindView(R.id.yiwancheng)
    RadioButton yiwancheng;
    @BindView(R.id.myradiogroup)
    MyRadioGroup myradiogroup;
    @BindView(R.id.task_vp)
    ViewPager taskVp;
    @BindView(R.id.add)
    HXTextView add;
    private List<Fragment> fragments;
    private TaskFragment daishouliFragment,chulizhongFragment,daijianchaFragment,yiwanchengFragment;
    public static final int UPDATE = 1001;
    public static final int DAI_SHOU_LI = 1;
    public static final int CHU_LI_ZHONG = 2;
    public static final int DAI_JIAN_CHA = 3;
    public static final int YI_WAN_CHENG = 5;
    private List<MenuBean> menuList;//

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_list);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        String authority = SPUtil.getString(this, "authority");
        if(!Utils.isEmpty(authority)){
            try{
                MenuListRes menuListRes = new Gson().fromJson(authority, MenuListRes.class);
                menuList = menuListRes.getValue();
            }catch (Exception e){
                Log.e(TAG, e.getMessage().toString());
            }
        }
        if(menuList == null){
            menuList = new ArrayList<>();
        }
        for (MenuBean menu:menuList){
            if(menu.getId() == 800){
                menu.setHasNew(false);
                for(MenuBean sMenu:menu.getData()){
                    if(sMenu.getId() == 810){
                        sMenu.setHasNew(false);
                    }
                }
            }
        }
        MenuListRes res = new MenuListRes();
        res.setValue(menuList);
        authority = new Gson().toJson(res);
        SPUtil.put(this, "authority", authority);
        Intent intent = new Intent();
        intent.setAction("update_menu");
        sendBroadcast(intent);

        if (hasAdd()) {
            add.setVisibility(View.VISIBLE);
        }

        myradiogroup.check(R.id.daishouli);
        initViewPager();
        getTaskCount();
        myradiogroup.setOnCheckedChangeListener(new MyRadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(MyRadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.daishouli:
                        taskVp.setCurrentItem(0);
                        break;
                    case R.id.chulizhong:
                        taskVp.setCurrentItem(1);
                        break;
                    case R.id.daijiancha:
                        taskVp.setCurrentItem(2);
                        break;
                    case R.id.yiwancheng:
                        taskVp.setCurrentItem(3);
                        break;
                }
            }
        });
    }

    @OnClick({R.id.iv_back, R.id.add})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_back:
                setResult(0);
                finish();
                break;
            case R.id.add:
                intent = new Intent(TaskListActivity.this, TaskCreateActivity.class);
                startActivityForResult(intent, 1);
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            setResult(0);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initViewPager(){
        fragments = new ArrayList<Fragment>();
        if(daishouliFragment == null){
            daishouliFragment = TaskFragment.newInstance(DAI_SHOU_LI);
        }
        fragments.add(daishouliFragment);
        if(chulizhongFragment == null){
            chulizhongFragment = TaskFragment.newInstance(CHU_LI_ZHONG);
        }
        fragments.add(chulizhongFragment);
        if(daijianchaFragment == null){
            daijianchaFragment = TaskFragment.newInstance(DAI_JIAN_CHA);
        }
        fragments.add(daijianchaFragment);
        if(yiwanchengFragment == null){
            yiwanchengFragment = TaskFragment.newInstance(YI_WAN_CHENG);
        }
        fragments.add(yiwanchengFragment);
        taskVp.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), fragments));
        taskVp.setCurrentItem(0);
        taskVp.addOnPageChangeListener(this);
    }

    public void getTaskCount() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(this,"constructionid"));
            if (!hasList()) {
                jsonObject.put("userId", SPUtil.getString(this, "userId"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        Utils.requestData(null, this, "/taskDistribution/queryCount/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    TaskCountRes taskCountRes = gson.fromJson(json, TaskCountRes.class);
                    if (taskCountRes.getValue().getPending() != 0) {
                        daishouliTv.setVisibility(View.VISIBLE);
                        daishouliTv.setText(taskCountRes.getValue().getPending() + "");
                    } else {
                        daishouliTv.setVisibility(View.GONE);

                    }

                    if (taskCountRes.getValue().getPendingInspection() != 0) {
                        daijianchaTv.setVisibility(View.VISIBLE);
                        daijianchaTv.setText(taskCountRes.getValue().getPendingInspection() + "");
                    } else {
                        daijianchaTv.setVisibility(View.GONE);
                    }

                    if (taskCountRes.getValue().getInTreatment() != 0) {
                        chulizhongTv.setVisibility(View.VISIBLE);
                        chulizhongTv.setText(taskCountRes.getValue().getInTreatment() + "");
                    } else {
                        chulizhongTv.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onFailure(String json) {
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == TaskListActivity.UPDATE) {
            for(Fragment fragment:fragments){
                ((TaskFragment)fragment).reLoad();
            }
            getTaskCount();
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        switch (position){
            case 0:
                myradiogroup.check(R.id.daishouli);
                break;
            case 1:
                myradiogroup.check(R.id.chulizhong);
                break;
            case 2:
                myradiogroup.check(R.id.daijiancha);
                break;
            case 3:
                myradiogroup.check(R.id.yiwancheng);
                break;
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
